﻿using System;
using System.Collections.Generic;
using System.Text;

namespace iTunesUtil
{
    public class SimilarityCheck<T>
    {
        private readonly SortedDictionary<string, List<T>> result = new SortedDictionary<string, List<T>>();

        public SortedDictionary<string, List<T>> Result
        {
            get { return result; }
        }
        public SimilarityCheck(IEnumerable<T> src, Converter<T, string> converter)
        {
            try
            {
                foreach (T t in src)
                {
                    string norm = Normalise(converter(t));
                    if (result.ContainsKey(norm))
                        result[norm].Add(t);
                    else
                    {
                        result.Add(norm, new List<T> { t });
                    }
                }
            }
            catch (Exception)
            {
                
            }            
        }

        public string Normalise(string s)
        {
            char lastChar = ' ';
            var sb = new StringBuilder();
            foreach (char c in s)
            {
                if (Char.IsDigit(c))
                {
                    sb.Append(c);
                    continue;
                }
                if (Char.IsLetter(c))
                {
                    char lc = Char.ToLower(c);
                    if ((lc >= 'a' && lc <= 'z') && lc != lastChar)
                    {
                        sb.Append(lc);
                        lastChar = lc;   
                    }
                }
            }
            return sb.ToString();
        }
    }
}
